package com.evaluationsystem.system.serivce.impl;

import cn.hutool.core.date.DateUtil;
import com.evaluationsystem.Utils.ModularNameUtils;
import com.evaluationsystem.Utils.PasswordUtils;
import com.evaluationsystem.Utils.UserContextUtils;
import com.evaluationsystem.system.dao.UserInfoDao;
import com.evaluationsystem.system.entity.Tlogs;
import com.evaluationsystem.system.entity.UserInfo;
import com.evaluationsystem.system.serivce.TlogsService;
import com.evaluationsystem.system.serivce.UserInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoDao dao;

    @Autowired
    UserContextUtils userContextUtils;

    @Autowired
    PasswordUtils passwordUtils;

    @Autowired
    TlogsService logsService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserInfo userInfo = dao.selectByvUsername(username);

        return userInfo;
    }

    @Override
    public int deleteByPrimaryKey(String vuserid) {
        return dao.deleteByPrimaryKey(vuserid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> insert(UserInfo record) {
        Map<String,Object> res = new HashMap<>();
        try {
            //判断 用户id是否重复
            if(!StringUtils.isEmpty(dao.UserIdByUserid(record.getUserid()))){
                res.put("code","5001");
                res.put("msg","账号已存在");
                return res;
            }
            record.setInsuserid(userContextUtils.getUser().getInsuserid()).setInsdate(DateUtil.today()).setPassword(passwordUtils.getHashPassword(record.getPassword()));
            int insert = dao.insert(record);
            insert = logsService.add(new Tlogs()
                    .setVoperationcontent(record.getUserid())/*操作内容*/
                    .setVmodularname(ModularNameUtils.UserInfo)/*操作模块名称*/
                    .setVpagename(ModularNameUtils.UserInfoAdd)/*操作页面名称*/
                    .setVoperation(userContextUtils.getUserId())/*操作人*/
                    /*.setVrecordscode(param.get("vstaffid").toString())*/
            );
            res.put("code","200");
            res.put("msg","保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.put("code","5000");
            res.put("msg","接口异常，请联系管理员");
        }
        return res;
    }

    @Override
    public int insertSelective(UserInfo record) {
        return dao.insertSelective(record);
    }

    @Override
    public UserInfo selectByPrimaryKey(String vuserid) {
        return dao.selectByPrimaryKey(vuserid);
    }

    @Override
    public int updateByPrimaryKeySelective(UserInfo record) {
        return dao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(UserInfo record) {
        return dao.updateByPrimaryKey(record);
    }

    @Override//{page=1, limit=10, vUserID=asdas, vUserName=dasd}
    public Map<String, Object> getTableList(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        PageHelper.startPage(Integer.parseInt(param.get("page").toString()), Integer.parseInt(param.get("limit").toString()));
        List<UserInfo> userInfos =  dao.selectUserInfoAll(param);
        PageInfo<UserInfo> userPageInfo = new PageInfo<>(userInfos);
        map.put("code","0");//解析接口状态
        map.put("msg","success");//解析提示文本
        map.put("count",userPageInfo.getTotal());//解析数据长度
        map.put("data",userPageInfo.getList());//解析数据列表
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> uptypeById(Map<String,Object> param) {
        Map<String,Object> res = new HashMap<>();
        try {
            /*{userid=1, username=1, password=null, insuserid=null, insdate=null, upduserid=null, upddate=null, vtypt=1}*/
            param.put("upduserid",userContextUtils.getUser().getUserid());
            param.put("upddate",DateUtil.today());
            param.put("vtypt",Integer.parseInt(param.get("vtypt").toString()));
            int a = dao.uptypeById(param);
            a = logsService.add(new Tlogs()
                .setVoperationcontent(param.get("startAndForbid").toString())/*操作内容*/
                .setVmodularname(ModularNameUtils.UserInfo)/*操作模块名称*/
                .setVpagename(ModularNameUtils.UserInfoUpdata)/*操作页面名称*/
                .setVoperation(userContextUtils.getUserId())/*操作人*/
                .setVrecordscode(param.get("userid").toString())
            );
            res.put("code","200");
            res.put("msg","修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.put("code","50001");
            res.put("msg","数据访问异常");
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> selectByUserId(Map<String,Object> param) {
        Map<String,Object> res = new HashMap<>();
        try {
            UserInfo userInfo = dao.selectByUserId(param);
            res.put("code","200");
            res.put("msg","ok");
            res.put("data",userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.put("code","50001");
            res.put("msg","数据访问异常");
        }
        return res;
    }

    @Override /*newUserid newUserName*/
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateUserByid(Map<String, Object> param) {
        System.out.println(param);
         /*{userid=emp, username=emp, password=null, insuserid=null,
        insdate=2020-15-3, upduserid=emp, upddate=2020-04-14, vtypt=0,
        newUserName=emp, newPassword=123123123}*/
        Map<String,Object> res = new HashMap<>();
        if(StringUtils.isNotEmpty(param.get("newPassword").toString())){
            param.put("password",passwordUtils.getHashPassword(param.get("newPassword").toString()));
        }
        param.put("upduserid",userContextUtils.getUser().getUserid());
        param.put("upddate",DateUtil.today());
        try {
            int a = dao.upInsertUser(param);
            a = logsService.add(new Tlogs()
                .setVoperationcontent(param.get("userid").toString())/*操作内容*/
                .setVmodularname(ModularNameUtils.UserInfo)/*操作模块名称*/
                .setVpagename(ModularNameUtils.UserInfoUpdata)/*操作页面名称*/
                .setVoperation(userContextUtils.getUserId())/*操作人*/
                .setVrecordscode(param.get("userid").toString())
            );
            res.put("code","200");
            res.put("msg","修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.put("code","5002");
            res.put("msg","数据访问异常");
        }
        return res;
    }


}
